# Clock - ClockLabel for Clutter
# Copyright (C) 2007 Lauri Taimila
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

__licence__ = "GPLv2"
__copyright__ = "2007, Lauri Taimila"
__author__ = "Lauri Taimila <lauri@taimila.com>"

import time
import gobject
import clutter

class ClockLabel(clutter.Label):
    """Clutter Label that displays current time."""
    
    def __init__(self):
        """Initialize Clock label"""
        clutter.Label.__init__(self)
        self._24_hour_clock = True
        #FIXME: Do we need to update on every second? Could it be synced to time
        #       and updated on every minute?
        self.update_clock_label()
        gobject.timeout_add(1000, self.update_clock_label)
        
    def set_use_24_hour_clock(self, boolean):
        """
        This method is used to determine time format of the clock. If paramter
        is set True, then we show time like "23:40" and if False then "11:40PM"
        @param boolean: Should we use 24h format
        """
        self._24_hour_clock = boolean
        
    def update_clock_label(self):
        """
        Callback function that updates Label's text to display current time.
        """
        # Get current time
        t = time.localtime()
        hours = str(t.tm_hour) 
        minutes = str(t.tm_min)

        # Add padding if needed: 14:2 -> 14:02
        if len(minutes) == 1:
            minutes = "0" + minutes
        if len(hours) == 1:
            hours = "0" + hours
        
        # Convert hours if needed
        if not self._24_hour_clock:
            if int(hours) > 12:
                hours = str(int(hours) - 12)
                suffix = "PM"
            else:
                suffix = "AM" 
            label = hours + ":" + minutes + suffix
        else:  
            label = hours + ":" + minutes
            
        self.set_text(label)
        return True
    